package com.nervenets.general;

import com.nervenets.general.event.SysLogEvent;
import com.nervenets.general.jwt.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.listener.AsyncConsumerRestartedEvent;
import org.springframework.amqp.rabbit.listener.AsyncConsumerStartedEvent;
import org.springframework.amqp.rabbit.listener.AsyncConsumerStoppedEvent;
import org.springframework.amqp.rabbit.listener.ConsumeOkEvent;
import org.springframework.boot.context.event.*;
import org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.ContextStoppedEvent;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.web.context.support.ServletRequestHandledEvent;
import springfox.documentation.schema.configuration.ObjectMapperConfigured;

import java.io.IOException;
import java.util.Arrays;


/**
 * SPRING-BOOT  生命周期监听器
 *
 * @author Administrator
 */
@Slf4j
public class ApplicationEventListener implements ApplicationListener<ApplicationEvent> {
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationEnvironmentPreparedEvent) { // 初始化环境变量
            log.info("###初始化环境变量");
        } else if (event instanceof ApplicationPreparedEvent) { // 初始化完成
            log.info("###初始化完成");
        } else if (event instanceof ContextRefreshedEvent) { // 应用刷新
            log.info("###应用刷新");
        } else if (event instanceof ApplicationReadyEvent) {// 应用启动准备就绪
            log.info("###应用启动准备就绪");
        } else if (event instanceof ContextStartedEvent) { // 应用启动，需要在代码动态添加监听器才可捕获
            log.info("###应用启动，需要在代码动态添加监听器才可捕获");
        } else if (event instanceof ContextStoppedEvent) { // 应用停止
            log.info("###应用停止");
        } else if (event instanceof ContextClosedEvent) { // 应用关闭
            log.info("###应用关闭");
        } else if (event instanceof ServletRequestHandledEvent) {
            /*ServletRequestHandledEvent handledEvent = (ServletRequestHandledEvent) event;
            log.info("{} {} {} 耗时{}:{}ms", handledEvent.getMethod(), handledEvent.getRequestUrl(), handledEvent.getStatusCode(), handledEvent.getProcessingTimeMillis() > 300 ? "太长" : "", handledEvent.getProcessingTimeMillis());
            if (handledEvent.wasFailure()) {
                log.error(handledEvent.getRequestUrl() + " handledWasFailure", handledEvent.getFailureCause());
            }*/
        } else if (event instanceof AsyncConsumerRestartedEvent) {
            AsyncConsumerRestartedEvent restartedEvent = (AsyncConsumerRestartedEvent) event;
            log.error("###消息队列服务似乎重启连接不上了？？" + restartedEvent);
        } else if (event instanceof ApplicationFailedEvent) {
            ApplicationFailedEvent failedEvent = (ApplicationFailedEvent) event;
            log.error("###应用启动失败", failedEvent.getException());
        } else if (event instanceof AsyncConsumerStoppedEvent) {
            AsyncConsumerStoppedEvent stoppedEvent = (AsyncConsumerStoppedEvent) event;
            log.error("###消息队列消费者已停止" + stoppedEvent);
        } else if (event instanceof AsyncConsumerStartedEvent) {
            AsyncConsumerStartedEvent startedEvent = (AsyncConsumerStartedEvent) event;
            log.info("###消息队列消费者开始启动" + startedEvent);
        } else if (event instanceof ConsumeOkEvent) {
            ConsumeOkEvent consumeOkEvent = (ConsumeOkEvent) event;
            log.info("###消息队列消费者已就续" + consumeOkEvent);
        } else if (event instanceof ServletWebServerInitializedEvent) {
            log.info("###应用初始化成功！");
            log.info("###检查权限冲突...");
            log.info("###成功扫描 {} 个项目权限！", JwtUtils.getAllMenuRoles().size());
        } else if (event instanceof ApplicationStartedEvent) {
            ConfigurableEnvironment environment = ((ApplicationStartedEvent) event).getApplicationContext().getEnvironment();
            final String[] activeProfiles = environment.getActiveProfiles();
            log.info("###恭喜您，应用启动成功！" + Arrays.toString(activeProfiles));
            String baseDomain = environment.getProperty("application.base-domain");
            log.info(String.format("http://%s/swagger-ui.html", baseDomain));

            if (Boolean.parseBoolean(environment.getProperty("application.auto-open-swagger", "false"))) {
                try {
                    Runtime.getRuntime().exec("cmd /c start " + String.format("http://%s/", baseDomain));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else if (event instanceof ObjectMapperConfigured) {
            log.info("###对象配置完成");
        } else if (event instanceof SysLogEvent) {
            //nothing to do
        } else {
            log.info("{}", event);
        }
    }

}
